package br.com.passeionaweb.appengine.tabelafipe.data;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;

public class DataProvider {

	private static final String BASE_URL = "http://quatrorodas.abril.com.br/compre-seu-carro/static/javascripts/";
	private static final String MAKE_URL = BASE_URL + "price-table-makes";
	private static final String MODEL_URL = BASE_URL + "price-table-models";
	private static final String YEAR_URL = BASE_URL + "price-table-years";
	private static final String VERSION_URL = BASE_URL + "price-table-versions";
	private static final String ENCODE = "utf-8";

	static public String getMakesJSON() throws IOException {
		URL url = new URL(MAKE_URL);
		getJSON(url);
		return getJSON(url);
	}

	static public String getModelsJSON() throws IOException {
		return getModelsJSON("");
	}

	static public String getModelsJSON(Make make) throws IOException {
		return getModelsJSON(make.getMake());
	}

	static public String getModelsJSON(String make) throws IOException {
		URL url = new URL(MODEL_URL + "?" + Make.KEY_MAKE + "=" + URLEncoder.encode(make, ENCODE));
		return getJSON(url);
	}

	static public String getYearsJSON() throws IOException {
		URL url = new URL(YEAR_URL);
		return getJSON(url);
	}

	static public String getYearsJSON(Make make, Model model) throws IOException {
		return getYearsJSON(make.getMake(), model.getModel());
	}

	static public String getYearsJSON(String make, String model) throws IOException {
		URL url = new URL(YEAR_URL + "?" + Make.KEY_MAKE + "=" + URLEncoder.encode(make, ENCODE)
				+ "&" + Model.KEY_MODEL + "=" + URLEncoder.encode(model, ENCODE));
		return getJSON(url);
	}

	static public String getVersionsJSON() throws IOException {
		return getVersionsJSON("", "", "");
	}

	static public String getVersionsJSON(Make make, Model model, Year year) throws IOException {
		return getVersionsJSON(make.getMake(), model.getModel(), year.getYear());
	}

	static public String getVersionsJSON(String make, String model, String year) throws IOException {
		URL url = new URL(VERSION_URL + "?" + Make.KEY_MAKE + "=" + URLEncoder.encode(make, ENCODE)
				+ "&" + Model.KEY_MODEL + "=" + URLEncoder.encode(model, ENCODE) + "&"
				+ Year.KEY_YEAR + "=" + URLEncoder.encode(year, ENCODE));
		return getJSON(url);
	}

	static public String getJSON(URL url) throws IOException {
		InputStream contentstream = (InputStream) url.getContent();

		StringBuilder builder = new StringBuilder();
		byte[] buffer = new byte[1024];
		while (contentstream.read(buffer) != -1) {
			builder.append(new String(buffer));
		}
		return builder.toString();
	}

}
